#!/usr/bin/perl

use strict;
use warnings;

use EBox::Global;
use EBox::Samba;
use TryCatch;

EBox::init();

my $global = EBox::Global->getInstance();
my $users = $global->modInstance('samba');

sub update
{
    foreach my $user (@{$users->users()}){
        my $username = $user->name();
        print "Checking user: $username\n";

        if ($user->hasValue('objectclass', 'userJabberAccount')) {
            print "User $username already has a Jabber account\n";
            next;
        }

        print "Adding Jabber account for user $username\n";
        my @objectclass = $user->get('objectclass');
        push (@objectclass, 'userJabberAccount');

        $user->set('objectclass', \@objectclass);
        $user->set('jabberUid', $user->name(), 1);
        $user->set('jabberAdmin', 'FALSE', 1);
        try {
            $user->save();
        } catch {
            warn "Error updating user: $username\n";
        }
    }
}

sub clean
{
    foreach my $user (@{$users->users()}) {
        $user->delete('jabberUid', 1) if $user->get('jabberUid');
        $user->delete('jabberAdmin', 1) if $user->get('jabberAdmin');

        my @objectclasses = $user->get('objectclass');
        @objectclasses = grep { $_ ne 'userJabberAccount' } @objectclasses;

        $user->set('objectClass', \@objectclasses);
        $user->save();
    }
}

sub usage {
    print "Usage: $0 update | clean\n";
    exit 1;
}

unless ($#ARGV == 0) {
    usage();
}

if ($ARGV[0] eq 'update') {
    update();
} elsif ($ARGV[0] eq 'clean') {
    clean();
} else {
    usage();
}

1;
